package il.ac.bgu.soa2009.hw6.impl;

import il.ac.bgu.soa2009.hw6.CinemaServiceServiceLocator;
import il.ac.bgu.soa2009.hw6.ClientPortType;
import il.ac.bgu.soa2009.hw6.cinema.Movie;
import il.ac.bgu.soa2009.hw6.cinema.Ticket;
import il.ac.bgu.soa2009.hw6.cinema.TicketRequest;
import org.apache.log4j.Logger;

import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.concurrent.Callable;

public class MovieReservationTask implements Callable<Ticket> {
    private static Logger logger = Logger.getLogger(MovieReservationTask.class);
    private String movieName;
    private Date date;
    private final CinemaServiceServiceLocator[] cinemaLocators;
    private final int ticketCount;

    public MovieReservationTask(String movieName, int ticketCount, Date date, CinemaServiceServiceLocator[] cinemaLocators) {
        this.movieName = movieName;
        this.date = date;
        this.cinemaLocators = cinemaLocators;
        this.ticketCount = ticketCount;
    }

    public Ticket call() throws NoSuchMovieException, ServiceException, RemoteException {
        CinemaServiceServiceLocator cinemaServiceServiceLocator = getCinemaLocatorForMovie(movieName.trim());
        if (cinemaServiceServiceLocator == null) {
            throw new NoSuchMovieException("No such movie : " + movieName);
        }//else continue
        il.ac.bgu.soa2009.hw6.ClientPortType cinemaClientService = cinemaServiceServiceLocator.getCinemaClientService();
        return cinemaClientService.orderTickets(new TicketRequest(movieName, date, ticketCount));//TODO change wsdl to get multiple tickets
    }


    private CinemaServiceServiceLocator getCinemaLocatorForMovie(String otherMovieName) {
        for (int i = 0; i < GoOutServiceImpl.getCinemaCount(); i++) {
            try {
                ClientPortType cinemaClientService = cinemaLocators[i].getCinemaClientService();
                Movie[] movies = cinemaClientService.getMovies();
                for (Movie movie : movies) {
                    String movieName = movie.getMovieName();
                    if (movieName != null) {
                        String trimedMoveName = movieName.trim();
                        if (trimedMoveName.equalsIgnoreCase(otherMovieName)) {
                            return cinemaLocators[i];
                        }
                    }
                }
            } catch (ServiceException e) {
                logger.error("Could not access cinema service: " + i, e);
            } catch (RemoteException e) {
                logger.error("Error while executing cinema request: " + i, e);
            }
        }
        return null;
    }
}
